package com.yunmasoft.service.pay.wexin.generic;

import com.house.ujiayigou.thirdpart.weixin.CryptoBase;
import com.house.ujiayigou.thirdpart.weixin.URLBuilder;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;

public class WxpayBase {
    // CONSTANTS
    public static final String KEY_KEY = "KEY";
    public static final String KEY_SIGN = "sign";
    public static final String KEY_SKIP_VERIFY_SIGN = "SKIP_VERIFY_SIGN";

    public static final String KEY_RETURN_CODE = "return_code";
    public static final String KEY_RETURN_MSG = "return_msg";
    public static final String KEY_RESULT_CODE = "result_code";
    public static final String KEY_ERR_CODE = "err_code";
    public static final String KEY_ERR_CODE_DES = "err_code_des";

    public static final String VALUE_SUCCESS = "SUCCESS";
    public static final String VALUE_FAIL = "FAIL";
    protected static CryptoBase crypto = CryptoBase.getInstance();
    // PROPERTIES
    public Properties respProp;

    /**
     * caculate sign according to wxp-spec
     *
     * @throws UnsupportedEncodingException if your runtime does not support utf-8.
     */
    protected String signMD5(List<String> paramNames, String key)
            throws UnsupportedEncodingException {
        if (key == null)
            throw (new IllegalArgumentException("KEY required to sign, but not found."));

        StringBuilder sb = new StringBuilder()
                .append(this.toQueryString(paramNames))
                .append("&key=" + key);

        String sign = this.crypto.byteToHex(
                this.crypto.MD5Digest(
                        sb.toString().getBytes("utf-8")
                ));

        sign = sign.toUpperCase();

        return (sign);
    }

    /**
     * Provide query string to sign().
     * toURL() may not invoke this method.
     */
    protected String toQueryString(List<String> paramNames) {
        URLBuilder ub = new URLBuilder();

        for (String key : paramNames) {
            if (KEY_SIGN.equals(key))
                continue;

            String value = this.getProperty(key);
            if (value == null || value.isEmpty())
                continue;

            ub.appendParam(key, value);
        }

        return (ub.toString());
    }

    public final String getProperty(String key) {
        return (this.respProp.getProperty(key));
    }


}
